<template>
  <v-layout>
    <template #header>
      <el-button type="primary" @click="toAdd" v-if="statelist" >添加</el-button>
    </template>
    <v-table url="/register/queryAllAdministrator" ref="tableRef">
      <v-column auto type="selection"></v-column>
      <v-column auto prop="name" label="用户名称"></v-column>
      <v-column auto prop="number" label="联系电话"></v-column>
      <v-column auto prop="type" label="人员类型">
        <template #default="{ row }">
          <div v-if="row.type=='3'">合作商</div>
          <div v-if="row.type=='1'">管理员</div>
          <div v-if="row.type=='2'">子用户</div>
        </template>
      </v-column>
      <v-column auto prop="field2" label="供应商信息">
        <template #default="{ row }">
          {{row.areaId}}
        </template>
      </v-column>
      <v-column auto prop="status" label="用户状态">
        <template #default="{ row }">
          <el-tag type="danger" v-if="row.status=='1'">禁用</el-tag>
          <el-tag type="success" v-else>启用</el-tag>
        </template>
      </v-column>
      <v-column auto prop="createTime" :formatter="dateFormat" label="创建时间"></v-column>
      <v-column auto label="操作">
        <template #default="scope">
          <el-button size="small" @click="toUp(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="toDel(scope.row)"
            >删除</el-button
          >
        </template>
      </v-column>
    </v-table>
  </v-layout>

  <v-dialog
    v-model="addVisible"
    title="新增"
    width="400px"
    @confirm="add"
    :action-loading="addLoading"
    @closed="addReset"
  >
    <el-form
      :model="addForm"
      :rules="rules"
      ref="addFormRef"
      label-position="top"
    >
      <el-form-item prop="name" label="用户姓名">
        <el-input
          placeholder="请输入用户姓名"
          v-model="addForm.name"
        ></el-input>
      </el-form-item>
      <el-form-item prop="areaId" label="供应商信息信息">
        <el-select v-model="addForm.areaId" placeholder="请选择供应商">
          <el-option
            v-for="item in vendorList"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="number" label="联系电话">
        <el-input
          placeholder="请输入联系电话"
          v-model="addForm.number"
        ></el-input>
      </el-form-item>
      
      <!-- <el-form-item prop="type" label="人员类型">
        <el-select v-model="addForm.type" placeholder="请选择人员类型">
          <el-option
            v-for="item in typeLi"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      
    </el-form>
  </v-dialog>
  <v-dialog
    v-model="upVisible"
    title="编辑"
    width="400px"
    @confirm="up"
    :action-loading="upLoading"
    @closed="upReset"
  >
    <el-form
      :model="upForm"
      ref="upFormRef"
      label-position="top"
    >
      <el-form-item prop="name" label="用户姓名">
        <el-input placeholder="请输入用户姓名" v-model="upForm.name"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="用户密码">
        <el-input placeholder="请输入新密码(非必填)" v-model="upForm.password"></el-input>
      </el-form-item>
      <el-form-item prop="areaId" label="供应商信息">
        <el-select v-model="upForm.areaId" placeholder="请选择供应商" disabled style="width: 360px;">
          <el-option
            v-for="item in vendorList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="number" label="联系电话">
        <el-input
          placeholder="请输入联系电话"
          v-model="upForm.number"
        ></el-input>
      </el-form-item>
      <el-form-item prop="status" label="用户状态">
        <el-radio-group v-model="upForm.status">
          <el-radio label="0">启用</el-radio>
          <el-radio label="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item prop="type" label="人员类型">
        <el-select v-model="upForm.type" placeholder="请选择人员类型" disabled>
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
    </el-form>
  </v-dialog>
</template>

<script setup lang="ts">
import { useTable } from "@/components/table/useTable";
import { useSubmit } from "@/hooks/useSubmit";
import { useUserStore } from "@/stores/user";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, type FormRules } from "element-plus";
import { markRaw, reactive, ref } from "vue";
import { getVendorData, insertUser, upUser ,deleteUser} from "@/api/user";
import type { vendorData, userData } from "@/api/user/model";

interface Data {
  id: string;
  name: string;
  number: string;
  password: string;
  type: string;
  areaId: string;
  status: string;
  createTime: string;
  phone: string;
}

const rules: FormRules = {
  number: [
    { required: true, message: "电话号码不能为空", trigger: "change" },
    { min: 11, max: 11, message: "电话号码长度为11位", trigger: "change" },
  ],
  name: [{ required: true, message: "名称不能为空", trigger: "change" }],
  type: [{ required: true, message: "类型不能为空", trigger: "change" }],
  areaId: [{ required: true, message: "供应商不能为空", trigger: "change" }],
};
//时间格式化
const dateFormat =  (row) => {
    let time = new Date(row.createTime)
    if(!time){
        return ''
    }
 
    var Y = time.getFullYear();
	var M = (time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1);
	var D = (time.getDate() < 10 ? '0' + time.getDate() : time.getDate());
	var h = (time.getHours() < 10 ? '0' + time.getHours() : time.getHours());
	var m = (time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes());
	var s = (time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds());
    return `${Y}/${M}/${D} ${h}:${m}:${s}`
}

const dateIfAddZero = (time) => {
    return time < 10 ? '0'+ time : time
}
const  statelist = ref(false)
const vendorList = ref<vendorData[]>([]);
const typeList = [
  {
    label: '管理员',
    value: '1',
  },
  
]
const typeLi = ref([])

const { tznUser } = useUserStore();

console.log(tznUser,'tznUser');
if(tznUser.type == '0'){
  statelist.value = true
}


//获取人员信息
getVendorData(tznUser.name).then((data) => {
  vendorList.value = data;
  if( tznUser.type == '1'){
    let typename =  typeList.slice(1)
    typeLi.value = typename
  }else{
    typeLi.value = typeList
  }
});

const { tableRef, getSelectionRows, reload } = useTable();

// 新增
const addForm = reactive<userData>({
  name: "",
  number: "",
  type: "",
  areaId: "",
});
const addVisible = ref(false);
const toAdd = () => {
  addVisible.value = true;
};
const {
  loading: addLoading,
  submit: add,
  formRef: addFormRef,
  reset: addReset,
} = useSubmit({
  form: addForm,
  ajax: async () => {
    await insertUser(addForm);
    ElMessage.success("添加人员信息成功");
    reload();
    addVisible.value = false;
  },
});

// 编辑
const upForm = reactive<userData>({
  id:"",
  name: "",
  number: "",
  type: "",
  areaId: "",
  status: "",
  password:""
});
const upVisible = ref(false);
const toUp = (row: Data) => {
  upVisible.value = true;
  upForm.id = row.id;
  upForm.name = row.name;
  upForm.number = row.number;
  upForm.type = row.type;
  upForm.areaId = row.areaId;
  upForm.status = row.status;
  //upForm.password = row.password;
};
const {
  loading: upLoading,
  submit: up,
  formRef: upFormRef,
  reset: upReset,
} = useSubmit({
  form: upForm,
  ajax: async () => {
    await upUser(upForm);
    ElMessage.success("编辑人员信息成功");
    reload();
    upVisible.value = false;
  },
});

// 删除
const toDel = (row?: Data) => {
  let delRows: Data[] = [];
  if (row) {
    // 单选删除
    delRows.push(row);
  } else {
    // 多选删除
    const selection = getSelectionRows();
    if (!selection || !selection.length) {
      ElMessage.warning("至少选择一条数据");
      return;
    }
    delRows = selection;
  }

  ElMessageBox.confirm("数据将被永久删除，是否确定？", "提示", {
    type: "warning",
    icon: markRaw(Delete),
    async callback(action: string) {
      if (action === "confirm") {
        // 发送删除请求
        await deleteUser(delRows[0].id);
        ElMessage.success("删除人员信息成功");
        reload();
      }
    },
  });
};
</script>
